import ajax from "@/utils/ajax";
import API from '@/api/index'
import * as echarts from 'echarts';
let RefreshList = null
export default {
  data() {
    return {
      screenshow: true,
      fictitiousshow: false,
      type: 1,
      listtype: 1,
      usertype: 1,
      //实时排名
      electricityconsumptiondata: [],
      temperatureRankdata: [],
      timeRankdata: [],
      powerrankdata: [],
      
      
      //历史排名
      historyelectricityconsumptiondata: [],
      historytemperatureRankdata: [],
      historytimeRankdata: [],
      historypowerrankdata: [],
      statisticsdata: {
        Usagetimes: 0,
        allUsagetimes: 0,
        allelectricityconsumption: 0,
        electricityconsumption: 0,
        allusagecount: 0,
        usagecount: 0,
        allcharge: 0,
        chargeinuse: 0,
        yearusagecount:0,
        yearelectricityconsumption:0,
        yearUsagetimes:0,
        weekusagecount:0,
        weekelectricityconsumption:0,
        weekUsagetimes:0,
        monthusagecount:0,
        monthelectricityconsumption:0,
        monthUsagetimes:0,
        usersNumber:0,
        weekusersNumber:0,
        monthusersNumber:0,
        yearusersNumber:0,

      },
      chargedata: [],
      chargedatasetdata:[],
      AllChargingPointInformationdata: [],
      Chargingpointtype: 1,
      ChargingPointInformationdata: [

      ],
      ChargingPointInformationshow: false,
      ChargingPointlocation: {
        x: 0,
        y: 0,
      },
      ChargingPointinfoshow: false,
      ChargingPointinfodata: {},
      ChargingDetailsworkstatedata: {
      },
      ChargingUserGendata: [],
      ChargingUserGenvidedata: [],
      ChargingUserGenvidedatashow: false,
      Charginghistorydata: [],
      Charginghistoryvidedata: [],
      Charginghistorydatashow: false,
      ChargingDetailsrowshow: false,
      rightsort: 305,
      currentsotr: 'asc',
      chargingDetailstype: 1,
      organId: null,
      poptitle: '',
      probeId: null,
      userId: null,
      ChargingDetailsworkstatetotldata: [
        {
          maxSt: 0,
          minSt: 0,
          avgSt: 0,
          maxSp: 0,
          minSp: 0,
          avgSp: 0,
          maxSv: 0,
          minSv: 0,
          avgSv: 0,
          maxSi: 0,
          minSi: 0,
          avgSi: 0,



        }
      ],
      loginusrid: this.$store.getters.user.id,
      organListdata: [],
      startColor: '',
      endColor: '',
      step: 30,
      colorArr: [],
      
      organIdtitle: '',
      todaykwh: 0,
      todaytime: 0,
      todaynow: 0,
      datetypeshow: false,
    
      rankween:[],
      rankmonth:[],
      rankyear:[],
      rankday:[],
      fictitious:{
       
        maxkwh:0,
        minkwh:0,
        avgkwh:0,
        totalactivePower:0,
        maxactivePower:0,
        minactivePower:0,
        avgactivePower:0,
        maxtemperature:0,
        mintemperature:0,
        avgtemperature:0,
       
        maxtime:0,
        mintime:0,
        avgtime:0,
        
      },
      statetab:3,
      goadmin:true
    }
  },
  created() {

  },
  mounted() {
    this.getOrganListdata()
   

  },
  beforeDestroy() {
    //清理定时器
    clearInterval(RefreshList);
  },
  filters: {
    usernamehide(value) {
      return value=='本地开启'?value:hideCode(value, 1, 1)
    }
  },
  computed: {
    //
    maintitle() {
      switch (this.type) {
        case 1:
          return "用电量";
        case 2:
          return "温度";
        case 3:
          return "使用时长";
        case 4:
          return "功率"
      }
    },
    maintitle2() {
     
      switch (this.type) {
        case 1:
          return "累计用电量(度)";
        case 2:
          return "历史最高温度(℃)";
        case 3:
          return "累计使用时长";
        case 4:
          return "历史最高功率(W)"
      
    }
    },
    randomnumreturn() {
      return function (row) {
    
      switch (this.type) {
        case 1:
          return row.kWh;
        case 2:
          return row.temperature;
        case 3:
          return this.calctime(row.Usagetime);
        case 4:
          return row.powerFactor;
      }
    }
    },
    daytitle() {
      switch (this.usertype) {
        case 2:
          return "日期";
        case 3:
          return "周序号";
        case 4:
          return "月份";
        case 5:
          return "年份";
        default:
          return ""
      }
    },
    //充电桩编码
    batteryNameCode() {
      return function (index) {
        let Code = index.split("-")
        return Code.slice(-1)[0].replace(/[^0-9]/ig, "") > 9 ? Code.slice(-1)[0].replace(/[^0-9]/ig, "") : "0" + Code.slice(-1)[0].replace(/[^1-9]/ig, "")
      }
    },
    ChargingPointlocationy() {
      return this.ChargingPointlocation.y - 150 + 'px'
    },
    ChargingPointlocationx() {
      return this.ChargingPointlocation.x + 30 + 'px'
    },
    chargetext() {
      return function (row) {
        switch (this.type) {
          case 1:
            return (row.kWh / 1000).toFixed(2) + '度'

          case 2:

            return row.temperature + '℃'
          case 3:

            return this.calctime(row.Usagetime)
          case 4:

            return row.powerFactor + 'W'
        }
      }
    },
    chargestyle() {
      return function (row) {
        let num
        if (row.state > 0) {
          switch (this.type) {
            case 1:
              num = row.kWh / 1000
              if (num > 30) {
                return 'kWhdanger'
              }
              else if (num > 20) {
                return 'kWhwarning'
              }
              else {
                return 'kWhnormal'
              }

            case 2:
              num = row.temperature
              if (num > 10) {
                return 'hot'
              }
              break;
            case 3:
              num = row.duration
              if (num > 10) {
                return 'timedanger'
              }
              else {
                return 'timenormal'
              }
            case 4:
              num = row.powerFactor
              if (num > 90) {
                return 'powerFactordanger'
              }
              else if (num > 60) {
                return 'powerFactorwarning'
              }
              else {
                return 'powerFactornormal'
              }

          }
        } else {
          return 'no-state'
        }
      }
    },
    
    //
    getranktitle(){
      return function () {
      
      switch (this.listtype) {
        case 1:
          return '实时'
        case 2:
            return this.getWeekopandend(new Date())
        case 3:
          return new Date().getMonth() + 1 + '月'
        case 4:
          return new Date().getFullYear()
      }
    }
    },

    //获取自然周
    getWeek() {
      return function (time) {
        let today = new Date(time); // 当天日期
        let firstDay = new Date(today.getFullYear(), 0, 1);
        let dayOfWeek = firstDay.getDay();
        let spendDay = 1;
        if (dayOfWeek != 0) {
          spendDay = 7 - dayOfWeek + 1;
        }
        firstDay = new Date(today.getFullYear(), 0, 1 + spendDay);
        let d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000);
        let result = Math.ceil(d / 7);
        return result + 1; // 直接返回第几自然周，如：34
      }
    },
    //周开始时间结束
    getWeekopandend() {
      return function (time) {
        let dayCode = new Date(time).getDay();


        let dayLong = 24 * 60 * 60 * 1000;
        let startDay = getFormatDatezhuanh(new Date(dayCode === 0 ? time - dayLong * 7 : time - dayLong * (dayCode - 1)))
        let endDay = getFormatDatezhuanh(new Date(dayCode === 0 ? time : time.getTime() + dayLong * (7 - dayCode)))

        return startDay.slice(5, 10) + ` ` + endDay.slice(5, 10)
      }
    },
    //充电桩记录序号
    ChargingDetailsHistorytitle() {
      return function (row) {
        switch (this.usertype) {
          case 2:
          
            return row.day?row.day.slice(5, 10):''
          case 3:
            return row.weekStartDay?'第' + this.getWeek(row.weekStartDay) + '周':''
          case 4:
            return row.monthStartDay?new Date(row.monthStartDay).getMonth() + 1 + '月':''
          case 5:
            return row.yearStartDay?row.yearStartDay.slice(0,4):''
          case 6:
            return '合计'
        }
      }
    },
    numbac(){
      return function(number){
         let numer = Math.floor(number)       
         if(String(numer).length < 4) 
         {
          numer = (Array(4).join(0) + numer).slice(-4)
         }
         let attr =numer.split('')
         let html=''
         for(let item of attr)
         {
           html+=`<font>${item}</font>`
         }
         
         return html
        }
    },
    //时间转换
    calctime() {
      return function (item) {
        if (item > 1) {
          let time = item / 60
          if (time < 59) {
            return  "00:"+ `${Math.floor(time % 60) <=9?'0':''}`+ (time % 60).toFixed(0) + ""
          } else {
            if(Math.floor(time / 60) > 1000){
              return Math.floor(time / 60) + ":00"
            }
            else{
             
              return `${Math.floor(time / 60) <= 9?'0':''}` + Math.floor(time / 60) + ":" + `${Math.floor(time % 60) <=9  ?'0':''}` + Math.floor(time % 60) + ""
            }
           
          }
        } else {
          return '-'
        }
      }
    },
    //时间转换
    calctimehtml() {
      return function (item) {
        let time = item / 60
        if (time < 60) {
          return `<font>${(time % 60).toFixed(0)}</font>` + "分"
        } else {
          return `<font>${Math.floor(time / 60)}</font>:<font>${(time % 60).toFixed(0)}</font>`
        }
      }
    },
     formatNumber() {
       return function(number){
      if (number >= 100) {
          number = number.toFixed(0)
      } else if (number >= 10) {
          number = number.toFixed(1)
      } else if (number > 0) {
          number = number.toFixed(2)
      } else if (number === 0) {
          number = number.toFixed(2)
      }else{
        number = number.toFixed(2)
      }
      return number
    }
  },
    getFormatDate() {
      return function (nowDate) {
        let date = nowDate==null?new Date():new Date(nowDate * 1000)
        let month = date.getMonth() + 1
        let strDate = date.getDate()
        let hours = date.getHours()
        let minutes = date.getMinutes()
        let seconds = date.getSeconds()
        if (month >= 1 && month <= 9) {
          month = '0' + month
        }
        if (strDate < 10) {
          strDate = '0' + strDate
        }
        if (hours < 10) {
          hours = '0' + hours
        }
        if (minutes < 10) {
          minutes = '0' + minutes
        }
        if (seconds < 10) {
          seconds = '0' + seconds
        }
        let currentDate = date.getFullYear() + '-' + month + '-' + strDate + ' ' + hours + ':' + minutes + ':' + seconds
        // console.log(currentDate)
        return currentDate
      }
    },
    //颜色计算2
    colorcacl2() {
      return function(row){
        let nowvalue
        switch (this.type) {
          case 1:
           
            nowvalue = row.kWh
            
            break;
          case 2:
          
            nowvalue = row.temperature
          
            break;
          case 3:
      
           
            nowvalue = row.Usagetime

            break;
          case 4:
         
            nowvalue = row.activePower
          
            break;
        }
        return this.colorArr[this.chargedatasetdata.findIndex((value)=>value==nowvalue)]
      }
    },
    //颜色计算3
    colorcacl3() {
      return function(row,type){
        let nowvalue
        switch (type) {
          case 1:
           
            nowvalue = row.kWh
            
            break;
          case 2:
          
            nowvalue = row.temperature
          
            break;
          case 3:
      
           
            nowvalue = row.Usagetime

            break;
          case 4:
         
            nowvalue = row.activePower
          
            break;
        }
        return this.colorArr[this.chargedatasetdata.findIndex((value)=>value==nowvalue)]
      }
    }
   
   
  },
  methods: {
    //获得客户网点
    getOrganListdata() {
      let self = this
      ajax.get({
        url: this.$API.getOrganList + this.loginusrid,
        showLoading: true,
        success: (response) => {
          if( response.data !=null){
          self.organListdata = response.data
          self.organId = response.data[0].id
          self.organIdtitle = response.data[0].name
          self.Chargingpointinformation()
          //60秒执行一次刷新
          self.getBatteryListfun()
          self.getBatteryProbeStatisticsfun()
          //演示用
          // self.changerBatteryListfun(1)
     
          // setTimeout(() => {
          //   self.changerBatteryListfun(2)
          // }, 1000);
          clearInterval(RefreshList)
          RefreshList = setInterval(() => {
            self.getBatteryListfun()


            self.getBatteryProbeStatisticsfun()

          }, 60000)



        }else{
          
          if(this.$store.getters.goadmin){
            this.$store.dispatch("actions/setGoadminAction", false);
            self.$router.push({ path: '/admin' })
            
          }
          // this.$store.dispatch("actions/setGoadminAction", false);
          // self.$router.push({ path: '/admin' })
        }
      }
      
      }
      )
    },
    //更换网点
    changeOrganid(selVal) {
      let self= this
      this.organIdtitle = this.organListdata.filter(item => item.id == selVal)[0].name
    
     
      self.Chargingpointinformation()
      //60秒执行一次刷新
      self.getBatteryListfun()
      self.getBatteryProbeStatisticsfun()
      self.ChargingPointinfoshow = false
      clearInterval(RefreshList)
      RefreshList = setInterval(() => {
        self.getBatteryListfun()


        self.getBatteryProbeStatisticsfun()

      }, 60000)

    },
    //充电桩总用电量,总时长
    getBatteryProbeStatisticsfun() {
      let self = this
      ajax.get({
        url: this.$API.getBatteryProbeTimeStatistics + self.organId,
        showLoading: true,
        success: (response) => {
          let mod = 1/3
          if (response.data != null) {
            self.statisticsdata.usagecount = response.data.chargeTimes
            self.statisticsdata.electricityconsumption = response.data.sqv
            self.statisticsdata.Usagetimes = response.data.chargeDuration
            self.statisticsdata.usersNumber = response.data.usersNumber?response.data.usersNumber:0
          }
          else{
            //Object.keys(self.statisticsdata).forEach(key=>{self.statisticsdata[key]=0})
            self.statisticsdata.usagecount =parseInt(10 * mod)
            self.statisticsdata.electricityconsumption = parseInt(7610 * mod)
            self.statisticsdata.Usagetimes = parseInt(184005 * mod)
            self.statisticsdata.usersNumber = parseInt(10 * mod)
          }
        }
      }
      )
      ajax.get({
        url: this.$API.getBatteryProbeStatistics + self.organId,
        showLoading: true,
        success: (response) => {
          let mod = 3/40
          let mo = 1/12
          if (response.data != null) {
            if(response.data.total != null){
              self.statisticsdata.allusagecount = response.data.total.chargeTimes
              self.statisticsdata.allelectricityconsumption = response.data.total.sqv
              self.statisticsdata.allUsagetimes = response.data.total.chargeDuration
              
            }else{
              self.statisticsdata.allusagecount = parseInt(5003 * mod * mo)
              self.statisticsdata.allelectricityconsumption = parseInt(3469824 * mod * mo)
              self.statisticsdata.allUsagetimes =  parseInt(86126938 * mod * mo)
            }
           
            if(response.data.month != null){
              self.statisticsdata.monthusagecount = response.data.month.chargeTimes
              self.statisticsdata.monthelectricityconsumption = response.data.month.sqv
              self.statisticsdata.monthUsagetimes = response.data.month.chargeDuration
              self.statisticsdata.monthusersNumber = response.data.month.usersNumber?response.data.month.usersNumber:0
              
            }else{
              self.statisticsdata.monthusagecount = parseInt(256 * mod)
              self.statisticsdata.monthelectricityconsumption = parseInt(182950 * mod)
              self.statisticsdata.monthUsagetimes = parseInt(4675220 * mod)
              self.statisticsdata.monthusersNumber = parseInt(240 * mod)
              
            }
            if(response.data.week != null){
              self.statisticsdata.weekusagecount = response.data.week.chargeTimes
              self.statisticsdata.weekelectricityconsumption = response.data.week.sqv
              self.statisticsdata.weekUsagetimes = response.data.week.chargeDuration
              self.statisticsdata.weekusersNumber = response.data.week.usersNumber?response.data.week.usersNumber:0
            }
            else{
              self.statisticsdata.weekusagecount = parseInt(196 * mod)
              self.statisticsdata.weekelectricityconsumption = parseInt(151110 * mod)
              self.statisticsdata.weekUsagetimes = parseInt(3803601 * mod)
              self.statisticsdata.weekusersNumber = parseInt(188 * mod)
            }
            if(response.data.year != null){
              self.statisticsdata.yearusagecount = response.data.year.chargeTimes
              self.statisticsdata.yearelectricityconsumption = response.data.year.sqv
              self.statisticsdata.yearUsagetimes = response.data.year.chargeDuration
              self.statisticsdata.yearusersNumber = response.data.year.usersNumber?response.data.year.usersNumber:0
            }else{
              self.statisticsdata.yearusagecount = parseInt(5003 * mod * mo)
              self.statisticsdata.yearelectricityconsumption = parseInt(3469824 * mod * mo)
              self.statisticsdata.yearUsagetimes = parseInt(86126938 * mod * mo)
              self.statisticsdata.yearusersNumber = parseInt(4732 * mod * mo)
            }
          }else{
            Object.keys(self.statisticsdata).forEach(key=>{self.statisticsdata[key]=0})
          
          }
        }
      }
      )
    },
    //获取充电桩列表
    getBatteryListfun() {
      let self = this
      ajax.get({
        url: this.$API.getBatteryList + self.organId,
        showLoading: true,
        success: (response) => {
          if (response.data != null) {
          
            this.$store.dispatch("actions/setGoadminAction", false);
            self.listprocessing(response.data)
          }
          else {
            
            if(this.$store.getters.goadmin){
              this.$store.dispatch("actions/setGoadminAction", false);
              self.$router.push({ path: '/admin' })
              
            }
            self.chargedata = []
            self.historyelectricityconsumptiondata = []
            self.historytemperatureRankdata = []
            self.historytimeRankdata = []
            self.historypowerrankdata = []
            Object.keys(self.statisticsdata).forEach(key=>{self.statisticsdata[key]=0})
            Object.keys(self.fictitious).forEach(key=>{self.fictitious[key]=0})
            this.todaykwh= 0
            this.todaynow= 0
            this.todaytime=0
          }
        },
      });
    },
    //列表排序
    listprocessing(data,type) {
      let self = this
      self.step = data.length
      //默认列表
      for (let item of data) {

        let Code = item.name != undefined ? item.name.split("-") : item.channelName.split("-")
        //console.log(item.name,item.temperature,item.duration)
        item.number = Code.slice(-1)[0].replace(/[^0-9]/ig, "") > 9 ? Code.slice(-1)[0].replace(/[^0-9]/ig, "") : "0" + Code.slice(-1)[0].replace(/[^1-9]/ig, "")
        item.activePower = item.probeSensorData != null ? item.probeSensorData.activePower : 0
        item.voltage = item.probeSensorData != null ? item.probeSensorData.voltage : 0
        item.temperature = item.probeSensorData != undefined ? item.probeSensorData.temperature : 0
        if (item.state != 0 && item.state != 2) {

          let Usagetime =   item.startTime !=null ? Math.round(new Date() / 1000) - (new Date(item.startTime)/ 1000)  :0
          //console.log(Usagetime)
          item.Usagetime = Math.abs(Usagetime)
          item.kWh = item.probeSensorData.electricQuantity - item.startElectricity
          //item.kWh = item.kWh < 0 ?0:item.kWh
          item.powerFactor  = item.probeSensorData != null ? item.probeSensorData.powerFactor : 0
        } else {
          item.Usagetime = 0
          item.kWh = 0
      
          item.activePower = 0
          item.powerFactor=0
          
        }
        if(item.batteryResult == undefined){
          item.batteryResult ={}
          
        }
    
     
      }
      if(self.listtype == 1){
        self.ranking(data,self.listtype)
      }
      let chargedataattr = [...data]

      chargedataattr = chargedataattr.sort((n1, n2) => {
        return n2.kWh - n1.kWh;
      });
      chargedataattr.forEach((item, i) => {
        item.ranking = i
      });
      
      self.chargedata = chargedataattr.sort((n1, n2) => {
        return n1.number - n2.number;
      });

      self.chargedata_sort()
      
        
        this.statisticsdata.chargeinuse = chargedataattr.filter(data => data.state > 0 && data.state !=2).length
        this.statisticsdata.allcharge = chargedataattr.length
        self.todaykwh = chargedataattr.reduce((sum, item) => sum + item.kWh, 0)
      
        self.todaytime = chargedataattr.reduce((sum, item) => sum + item.Usagetime, 0)
        self.todaynow = this.statisticsdata.chargeinuse
        self.fictitious.avgkwh= this.statisticsdata.chargeinuse > 0?self.todaykwh /  self.statisticsdata.chargeinuse:'0'
        self.fictitious.avgtime= self.todaytime /  self.statisticsdata.chargeinuse 
        self.fictitious.avgtemperature= (chargedataattr.reduce((sum, item) => sum + item.temperature, 0) /  this.statisticsdata.allcharge).toFixed(0)
        self.fictitious.totalactivePower = chargedataattr.reduce((sum, item) => sum + item.activePower, 0)
        self.fictitious.avgactivePower=  this.statisticsdata.chargeinuse > 0 ? (self.fictitious.totalactivePower /  self.statisticsdata.chargeinuse).toFixed(0) :'-'
        
        self.fictitious.maxkwh= Math.max.apply(null, chargedataattr.map(item => item.kWh))
        self.fictitious.minkwh= Math.min.apply(null, chargedataattr.map(item => item.kWh))
        self.fictitious.maxactivePower= this.statisticsdata.chargeinuse >0 ?Math.max.apply(null, chargedataattr.map(item => item.activePower)):'-'
        self.fictitious.minactivePower= this.statisticsdata.chargeinuse > 0 ?Math.min.apply(null, chargedataattr.filter(data => data.state > 0 && data.state !=2).map(item => item.activePower)):'-'
        self.fictitious.maxtemperature= Math.max.apply(null, chargedataattr.map(item => item.temperature))
        self.fictitious.mintemperature= Math.min.apply(null, chargedataattr.map(item => item.temperature))
        self.fictitious.maxtime= Math.max.apply(null, chargedataattr.map(item => item.Usagetime))
        
        self.fictitious.mintime= this.statisticsdata.chargeinuse > 0 ? Math.min.apply(null, chargedataattr.filter(data => data.state > 0 && data.state !=2 && data.Usagetime !=0 ).map(item => item.Usagetime)):'-'
    },
    ranking(data,type){ //用电前10
     let self =this
      let toptennum = 4
      let kWhttr = [...data]
    
     
    
      self.historyelectricityconsumptiondata = kWhttr.sort((n1, n2) => {
        return n2.kWh - n1.kWh;
      }).slice(0, toptennum)
    
      //温度前10
      let temattr = [...data]
   
     
      self.historytemperatureRankdata = temattr.sort((n1, n2) => {
        return n2.temperature - n1.temperature;
      }).slice(0, toptennum)

      //使用时间前10
      let timettr = [...data]
     
      if (self.listtype == 1) {
        timettr = timettr.filter(data => data.state > 0 && data.state !=2)
      }
      self.historytimeRankdata = timettr.sort((n1, n2) => {
        return n2.Usagetime - n1.Usagetime;
      }).slice(0, toptennum)

      //功率前10
      let powerttr = [...data]
     
      self.historypowerrankdata = powerttr.sort((n1, n2) => {
        return n2.activePower - n1.activePower;
      }).slice(0, toptennum)

      if(type==1){
        self.electricityconsumptiondata=self.historyelectricityconsumptiondata
        self.temperatureRankdata=self.historytemperatureRankdata
        self.timeRankdata=self.historytimeRankdata
        self.powerrankdata=self.historypowerrankdata

      }
    },
    //列表数据切换
    changerBatteryListfun(type) {
      let self = this
      self.listtype = type
      self.datetypeshow=false
      switch (type) {
        case 1:
          this.ranking(this.chargedata,1)
          break;
      
        case 2:
          this.ranking(this.rankween,2)
          break;
        case 3:
          this.ranking(this.rankmonth,3)
          break;
        case 4:
          this.ranking(this.rankyear,4)
          break;
        case 5:
            this.ranking(this.rankday,5)
            break;
      }

  
    },
   
    //日、周、月统计、
    Chargingpointinformation() {
    
      let self = this
      ajax.get({
        url: this.$API.getBatteryAllProbeViews + self.organId,
        showLoading: true,
        success: (response) => {
          self.AllChargingPointInformationdata = response.data
          this.rankween=[]
          this.rankmonth=[]
          this.rankyear=[]
          this.rankday=[]
          for (let item in this.AllChargingPointInformationdata) {
            if ((this.AllChargingPointInformationdata[item].week ?? '') !== '') {
             
              this.rankween.push(rankdataret(this.AllChargingPointInformationdata[item].week))
            }
            if ((this.AllChargingPointInformationdata[item].month ?? '') !== '') {
              this.rankmonth.push(rankdataret(this.AllChargingPointInformationdata[item].month))
            }
            if ((this.AllChargingPointInformationdata[item].year ?? '') !== '') {
              this.rankyear.push(rankdataret(this.AllChargingPointInformationdata[item].year))
            }
            if ((this.AllChargingPointInformationdata[item].day ?? '') !== '') {
              this.rankday.push(rankdataret(this.AllChargingPointInformationdata[item].day))
            }
          }
         
          
        }
      })

    
    },
    screenChargingPointInformationdatafun(type) {
      this.ChargingPointInformationdata = []
      this.Chargingpointtype=type
      this.ChargingPointInformationshow = true
      switch (type) {
        case 1:
        
          this.ChargingPointInformationdata=this.rankween
          break;
        case 2:
        
          this.ChargingPointInformationdata=this.rankmonth
          break;
        case 3:
        
          this.ChargingPointInformationdata=this.rankyear
          break;

      }

    },
    //鼠标移入显示
    chargemouseenter(e, id, row) {
      this.ChargingPointinfoshow = true
      
      let rowwidth = this.$refs.maincenter.clientWidth
      this.ChargingPointlocation.x = e.clientX + 400 > rowwidth ? e.clientX - 500 : e.clientX + 50
      this.ChargingPointlocation.y = e.clientY - 50

      this.ChargingPointinfodata = { ...row }

    },
    ChargingDetails(id, row) {
      this.ChargingDetailsrowshow = true
      this.chargingDetailstype=1
      this.poptitle = row.number
      this.probeId = row.probeId
      this.userId = row.userId
  
      this.ChargingDetailsworkstatedata = { ...row }
      
      ajax.get({
        url: this.$API.getBatteryProbeTotal + row.probeId,
        showLoading: true,
        success: (response) => {
          if (response.data.length > 0) {
            this.ChargingDetailsworkstatetotldata = response.data[0]
          } else {
            this.ChargingDetailsworkstatetotldata = this.ChargingDetailsworkstatetotldata[0]
          }
        }
      })
    },
    headerRowStyle(obj) {

      if (obj.column.label == "herad") {
        return "heradclass"
      } else if (obj.column.label == "heradleve2") {
        return "heradleve2class"
      }
    },
    sorttypechange(e) {
      // this.currentsotr = 'default'
      this.chargedata_sort()
      // switch (e) {
      //   case 1:
      //     this.rightsort = 305

      //     break;
      //   case 2:
      //     this.rightsort = 225
      //     break;
      //   case 3:
      //     this.rightsort = 115
      //     break;
      //   case 4:
      //     this.rightsort = 30
      //     break;
      // }

    },
    // chargedata_sort(sort,n) {
    chargedata_sort() {
      // this.currentsotr = this.currentsotr == sort && n != 3 ? 'default' : sort

      let self = this

      let chargedatasort = [...this.chargedata]
      let step
      chargedatasort = chargedatasort.sort((n1, n2) => {
        return n2.state - n1.state;
      });
      self.chargedatasetdata=[]
      self.step = self.chargedata.length
      switch (this.type) {
        case 1:
          
          chargedatasort = chargedatasort.sort((n1, n2) => {
            return n2.kWh - n1.kWh;
          });
          for(let item of chargedatasort){
            self.chargedatasetdata.push(item.kWh)
          }
          self.chargedatasetdata =setdata(self.chargedatasetdata)
          step = self.chargedatasetdata.length
        
          self.startColor = "#008600"
          self.endColor = "#77c676"
          self.colorArr = gradient(self.startColor, self.endColor,step)
          
          break;
        case 2:

          chargedatasort = chargedatasort.sort((n1, n2) => {
            return n2.temperature - n1.temperature;
          });
          for(let item of chargedatasort){
            self.chargedatasetdata.push(item.temperature)
          }
          self.chargedatasetdata =setdata(self.chargedatasetdata)
          step = self.chargedatasetdata.length
        
          self.startColor = "#910000"
          self.endColor = "#f35050"
          self.colorArr = gradient(self.startColor, self.endColor, step)
          break;
        case 3:
          chargedatasort = chargedatasort.sort((n1, n2) => {
            return n2.Usagetime - n1.Usagetime;
          });
          for(let item of chargedatasort){
            self.chargedatasetdata.push(item.Usagetime)
          }
          self.chargedatasetdata =setdata(self.chargedatasetdata)
          step = self.chargedatasetdata.length
       
          self.startColor = "#ac4200"
          self.endColor = "#e17b4a"
          self.colorArr = gradient(self.startColor, self.endColor, step)
         
          break;
        case 4:
          chargedatasort = chargedatasort.sort((n1, n2) => {
            return n2.activePower - n1.activePower;
          });
          for(let item of chargedatasort){
            self.chargedatasetdata.push(item.activePower)
          }
          self.chargedatasetdata =setdata(self.chargedatasetdata)
          step = self.chargedatasetdata.length

          self.startColor = "#84006e"
          self.endColor = "#ec58d6"
          self.colorArr = gradient(self.startColor, self.endColor, step)
          break;
      }
      chargedatasort.forEach((item, i) => {
        item.ranking = i
      });
      if (this.currentsotr == 'desc') {
        this.chargedata = chargedatasort.sort((n1, n2) => {
          return n2.ranking - n1.ranking;
        });

      } else if (this.currentsotr == 'asc') {

        this.chargedata = chargedatasort.sort((n1, n2) => {
          return n1.ranking - n2.ranking;
        });

      }
      else {
        this.chargedata = chargedatasort.sort((n1, n2) => {
          return n1.number - n2.number;
        });
      }
    },
    chargingDetailstype_change(type) {
      this.chargingDetailstype = type
      this.Charginghistorydatashow = false
      this.ChargingUserGenvidedatashow = false
      if (type != 1) {
        this.getChargingDetailsuserData()
      }
    },
    //充电日志(时间+用户id)
    getBatteryLogByTimeAndUserIdfun(row) {
      let self = this
      let currTime
      let endTime
      let startTime
      let urlling
    
      if (this.chargingDetailstype == 2) {
        urlling = self.$API.getBatteryLogByTimeAndUserId + self.userId
      }
      else if (this.chargingDetailstype == 3) {
        urlling = self.$API.getBatteryLogByTimeAndProbeId + self.probeId
      }
      let date
      switch (self.usertype) {
        case 1:
          switch (row.type) {
            case '当日':
              currTime = row.day.slice(0, 10)
              urlling += `?currTime=${currTime}`
              break;
            case '当周':
              startTime = row.weekStartDay.slice(0, 10)
              date = new Date(row.weekStartDay)

              endTime = getFormatDatezhuanh(new Date(date.setDate(date.getDate() + 6))).slice(0, 10)
              urlling += `?startTime=${startTime}&endTime=${endTime}`
              break;
            case '当月':
              startTime = row.monthStartDay.slice(0, 10)
              endTime = monthendtime(row.monthStartDay).slice(0, 10)
              urlling += `?startTime=${startTime}&endTime=${endTime}`
              break;
            case '当年':
              startTime = row.yearStartDay.slice(0, 4) + "-01-01"
              endTime = row.yearStartDay.slice(0, 4) + "-12-31"
              urlling += `?startTime=${startTime}&endTime=${endTime}`
              break;
          }
          break;
        case 2:
          currTime = row.day.slice(0, 10)
          urlling += `?currTime=${currTime}`
          break
        case 3:
          startTime = row.weekStartDay.slice(0, 10)
          date = new Date(row.weekStartDay)
          endTime = getFormatDatezhuanh(new Date(date.setDate(date.getDate() + 6))).slice(0, 10)
          urlling += `?startTime=${startTime}&endTime=${endTime}`
          break
        case 4:
          startTime = row.monthStartDay.slice(0, 10)
          endTime = monthendtime(row.monthStartDay).slice(0, 10)
          urlling += `?startTime=${startTime}&endTime=${endTime}`
          break;
        case 5:
          startTime = row.yearStartDay.slice(0, 4) + "-01-01"
          endTime = row.yearStartDay.slice(0, 4) + "-12-31"
          urlling += `?startTime=${startTime}&endTime=${endTime}`
          break;
        case 6:
          date = getFormatDatezhuanh(new Date())
          startTime = "2020-01-01"
          endTime = date.slice(0, 4) + "-12-31"
          urlling += `?startTime=${startTime}&endTime=${endTime}`
          break;
      }
      ajax.get({
        url: urlling,
        showLoading: true,
        success: (response) => {
          if (self.chargingDetailstype == 2) {
            self.ChargingUserGenvidedata = response.data
            self.ChargingUserGenvidedatashow = true
            self.Charginghistorydatashow = false
          } else if (self.chargingDetailstype == 3) {
            self.ChargingUserGenvidedata = response.data
            self.ChargingUserGenvidedatashow = false
            self.Charginghistorydatashow = true
          }
        }
      })

    },
    //关闭充电桩
    closeCharg(type) {
     let text=type=='open'?'开启':'关闭'
        this.$prompt('', {
        title:'再次确定',
        dangerouslyUseHTMLString: true,
        message:`确定${text}充电桩，请输入<font style='color:#f00'>12345</font>。`,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator(value){
          if ((value?? '') == '' ) {
            return '输入确定信息不能为空'}
          else if(value != 12345){
            return '输入确定信息不正确'
          }
          },
        inputErrorMessage: '输入信息不正确'
      }).then(() => {
        ajax.post({
          url: this.$API.probeOperation,
          data: { id: this.ChargingDetailsworkstatedata.probeId, channel: 1 },
          success: (response) => {
            //console.log(response)
            if (response.success) {
              this.getBatteryListfun()
              this.$message({
                type: 'success',
                message: `${text}成功`
              });
            }else{
                this.$message({
                  message: response.message,
                  type: 'warning'
                });
            }
          },
         });
       
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消关闭'
        });       
      });
    },
    getChargingDetailsuserData() {
      let getlink
      let self = this

      if (this.chargingDetailstype == 3) {
        self.Charginghistorydata = []
        switch (this.usertype) {
          case 1:
            getlink = this.$API.getBatteryProbeViews
            break;
          case 2:
            getlink = this.$API.getBatteryProbeDay
            break;
          case 3:
            getlink = this.$API.getBatteryProbeWeek
            break;
          case 4:
            getlink = this.$API.getBatteryProbeMonth
            break;
          case 5:
            getlink = this.$API.getBatteryProbeYear
            break;
          case 6:
            getlink = this.$API.getBatteryProbeTotal
            break;
        }

        ajax.get({
          url: getlink += self.probeId,
          showLoading: true,
          success: (response) => {

            if (this.usertype == 1) {
              if(!(new Date().getTime() - new Date(response.data.day).getTime() < (24 * 60 * 60* 1000))){
                Object.keys(response.data.day).forEach(key=>{response.data.day[key]='-'})
              }
              else{
                response.data.day.type = "当日"
                self.Charginghistorydata.push(response.data.day)
              }
             
              response.data.week.type = "当周"
              response.data.month.type = "当月"
              response.data.year.type = "当年"
          
              self.Charginghistorydata.push(response.data.week)
              self.Charginghistorydata.push(response.data.month)
              self.Charginghistorydata.push(response.data.year)
            } else {
              self.Charginghistorydata = response.data
            }
          }
        })
      }
      else if (this.chargingDetailstype == 2) {
        self.ChargingUserGendata = []
        switch (this.usertype) {
          case 1:
            getlink = this.$API.getBatteryUserViews
            break;
          case 2:
            getlink = this.$API.getBatteryUserDay
            break;
          case 3:
            getlink = this.$API.getBatteryUserWeek
            break;
          case 4:
            getlink = this.$API.getBatteryUserMonth
            break;
          case 5:
            getlink = this.$API.getBatteryUserYear
            break;
          case 6:
            getlink = this.$API.getBatteryUserTotal
            break;
        }

        ajax.get({
          url: getlink += self.userId,
          showLoading: true,
          success: (response) => {

            if (this.usertype == 1) {
           
              if(!(new Date().getTime() - new Date(response.data.day).getTime() < (24 * 60 * 60 * 1000))){
                Object.keys(response.data.day).forEach(key=>{response.data.day[key]='-'})
               
              }
             else{
              response.data.day.type = "当日"
              self.ChargingUserGendata.push(response.data.day)
             }
             
             
              response.data.week.type = "当周"
              response.data.month.type = "当月"
              response.data.year.type = "当年"
              
             
              self.ChargingUserGendata.push(response.data.week)
              self.ChargingUserGendata.push(response.data.month)
              self.ChargingUserGendata.push(response.data.year)

            } else {
              self.ChargingUserGendata = response.data
            }

          }
        })
      }

    },
  },
  watch: {
    usertype(val) {
      this.Charginghistorydatashow = false
      this.ChargingUserGenvidedatashow = false
      this.getChargingDetailsuserData()
    }
  }
}
function getFormatDatezhuanh(nowDate) {
  let date = nowDate
  let month = date.getMonth() + 1
  let strDate = date.getDate()
  let hours = date.getHours()
  let minutes = date.getMinutes()
  let seconds = date.getSeconds()
  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate < 10) {
    strDate = '0' + strDate
  }
  if (hours < 10) {
    hours = '0' + hours
  }
  if (minutes < 10) {
    minutes = '0' + minutes
  }
  if (seconds < 10) {
    seconds = '0' + seconds
  }
  let currentDate = date.getFullYear() + '-' + month + '-' + strDate + ' ' + hours + ':' + minutes + ':' + seconds
  // console.log(currentDate)
  return currentDate
}
function monthendtime(data) {
  let nowDate = new Date(data);
  let cloneNowDate = new Date(data);
  let fullYear = nowDate.getFullYear();
  let month = nowDate.getMonth() + 1; // getMonth 方法返回 0-11，代表1-12月 
  let endOfMonth = new Date(fullYear, month, 0).getDate(); // 获取本月最后一天
  let endDate = getFormatDatezhuanh(new Date(cloneNowDate.setDate(endOfMonth)))//当月最后一天 
  return endDate
}

// rgb to hex
function rgbToHex(r, g, b) {
  let hex = ((r << 16) | (g << 8) | b).toString(16);
  return "#" + new Array(Math.abs(hex.length - 7)).join("0") + hex;
}

// hex to rgb
function hexToRgb(hex) {
  let rgb = [];
  for (let i = 1; i < 7; i += 2) {
    rgb.push(parseInt("0x" + hex.slice(i, i + 2)));
  }
  return rgb;
}

// 计算渐变过渡色
function gradient(startColor, endColor, step) {
  // 将 hex 转换为rgb
  var sColor = hexToRgb(startColor),
    eColor = hexToRgb(endColor);

  // 计算R\G\B每一步的差值
  let rStep = (eColor[0] - sColor[0]) / step
  let gStep = (eColor[1] - sColor[1]) / step;
  let bStep = (eColor[2] - sColor[2]) / step;

  let gradientColorArr = [];
  for (let i = 0; i < step; i++) {
    // 计算每一步的hex值
    gradientColorArr.push(rgbToHex(parseInt(rStep * i + sColor[0]), parseInt(gStep * i + sColor[1]), parseInt(bStep * i + sColor[2])));
  }
  return gradientColorArr;
}
function randomnum(min,max){
    return Math.floor(Math.random()*(max-min+1)+min)
}
function setdata(data){
  return [...new Set(data)]
}
function rankdataret(data){
  let attr = {}
  let Code = data.probeChannelName.split("-")
  //console.log(item.name,item.temperature,item.duration)
  attr.id= data.id
  attr.number= Code.slice(-1)[0].replace(/[^0-9]/ig, "") > 9 ? Code.slice(-1)[0].replace(/[^0-9]/ig, "") : "0" + Code.slice(-1)[0].replace(/[^1-9]/ig, "")
  attr.activePower= data.maxSp
  attr.avgSp= data.avgSp
  attr.Usagetime=data.chargeDuration
  attr.chargeTimes=data.chargeTimes
  attr.avgtime= data.chargeDuration / data.chargeTimes
  attr.temperature=data.maxSt
  attr.minSt=data.minSt
  attr.avgSt=data.avgSt
  attr.kWh=data.sqv
  return attr
}
function hideCode(str, frontLen, endLen) {
  // let len = str.length - frontLen - endLen;
  // let xing = '';
  // for (var i = 0; i < len; i++) {
  //   xing += '*';
  // }
  return str?str.substring(0, str.length - 2) + '*' +str.substring(str.length,str.length -1):''

}